import axios from "axios";
import Storage from "./Storage";
import Constants from "expo-constants";
// console.log("Constants.easConfig.extra" , Constants.easConfig.extra);

interface ApiResponse<T = any> {
	code: number; // 服务端定制的状态码
	data: T; // 响应的实际数据
	message?: string; // 错误或提示信息
}

const http = axios.create({
	baseURL: "https://aicenter.luyantech.com",
	timeout: 50000,
});
/* 
请求拦截器
*/
http.interceptors.request.use(
	async (config) => {
		const uuid = (await Storage.getStorage("uuid")) || "";
		config.headers["uuid"] = uuid; // 添加 uuid 到请求头
		config.headers["app"] = "xmch1"; // 固定 app 值
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);

/* 
对返回体错误信息进行分类处理
*/
http.interceptors.response.use(
	(res) => res.data,
	(error) => {
		const { response } = error;
		if (response) {
			const { status } = response;
			if (status >= 500) {
				// 服务端报错
			} else if (status === 400) {
				// 接口参数异常
			} else if (status === 401) {
				// 登陆信息过期，需要重新登陆
			} else {
				// 其它错误类型，统一按照接口报错处理
			}
		} else {
			// 网络异常
		}
		return Promise.reject(error);
	}
);

// 封装get方法
export const get =  <T>(url: string, params?: any) =>
	http.get<ApiResponse<T>>(url, { params: params });

// 封装post方法
export const post = <T> (url: string, data: any ,  contentType?: string) => {
	return http.post<ApiResponse<T>>(url, data , {
		headers:{
			'Content-Type': contentType || 'application/json', // 如果没有传入，使用默认值
		}
	});
}
